package me.shingohu.man.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.yatatsu.autobundle.AutoBundle;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
import me.shingohu.man.R;
import me.shingohu.man.intergation.BugtagsManager;

/**
 * Created by hujie on 17/4/14.
 *
 *
 * SupportActivity
 *
 * rxlifecycle https://github.com/trello/RxLifecycle
 */

abstract class BaseActivity extends me.yokeyword.fragmentation.SupportActivity implements LifecycleProvider<ActivityEvent> {
    protected Activity mActivity;
    protected TextView mTitleTV;
    private Unbinder mUnbinder;
    protected View mStatusView;//状态栏
    protected Toolbar mToolbar;
    protected ViewGroup mRootView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setupWindowsFeature();
        super.onCreate(savedInstanceState);
        lifecycleSubject.onNext(ActivityEvent.CREATE);
        mActivity = this;
        autoBindBundle(savedInstanceState);
        setUpView();
        bindView();
        registerEventBus();
    }

    public ViewGroup getRootView() {
        return mRootView;
    }

    /**
     * 是否支持toolbar作为导航栏
     * 如果不需要导航栏 则return false
     * @return
     */
    public boolean supportActionbar() {
        return true;
    }


    private void setUpRootView() {
        mRootView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.root_layout, null);
    }

    protected void setUpView() {
        setUpRootView();
        setUpStatusBarView();
        setUpToolBarView();
        setContentView();
    }

    private void setContentView() {
        if (layoutId() != 0) {
            View contentView = LayoutInflater.from(this).inflate(layoutId(), null);
            mRootView.addView(contentView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            setContentView(mRootView);
            setUpCustomToolbar();
        }
    }

    /**
     * 设置状态栏
     */
    private void setUpStatusBarView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            mStatusView = LayoutInflater.from(this).inflate(R.layout.status_bar, null);
            mRootView.addView(mStatusView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, BarUtils.getStatusBarHeight(mActivity  )));
        }
    }

    /**
     * 设置导航栏
     */
    private void setUpToolBarView() {
        if (supportActionbar()) {
            Toolbar toolbar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.actionbar, null);
            installToolbar(toolbar);
            mRootView.addView(toolbar);
            toolbar.setOnTouchListener((v, event) -> {
                KeyboardUtils.hideSoftInput(this);
                return false;
            });
        }
    }

    /**
     * 关联布局中子定义的toolbar
     */
    public void setUpCustomToolbar() {
        if (mRootView != null && !supportActionbar()) {
            Toolbar toolbar = (Toolbar) mRootView.findViewById(R.id.actionbar);
            if (toolbar != null) {
                installToolbar(toolbar);
            }
        }
    }


    private void installToolbar(Toolbar toolbar) {
        this.mToolbar = toolbar;
        this.mTitleTV = (TextView) mToolbar.findViewById(R.id.toolbarTitleTV);
        this.mTitleTV.setSelected(true);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        setBackNavication();
    }


    /**
     * 状态栏隐藏显示*/
    protected void setStatusBarViewVisibility(int visibility) {
        if (mStatusView != null) {
            mStatusView.setVisibility(visibility);
        }
    }

    /**
     * 导航栏隐藏显示*/
    protected void setToolBarViewVisibility(int visibility) {
        if (mToolbar != null) {
            mToolbar.setVisibility(visibility);
        }
    }


    /**
     * 是否显示返回按钮
     * @return
     */
    public boolean showBackNavication() {
        return true;
    }

    /**
     * 设置返回导航
     */
    private void setBackNavication() {
        if (mToolbar != null && showBackNavication()) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationContentDescription("返回");
            mToolbar.setNavigationOnClickListener(v -> onBackPressed());

        } else {
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        }
    }


    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        setTitle(title, color);

    }


    private void setTitle(CharSequence title, int color) {
        if (mTitleTV != null) {
            if (color != 0) {
                mTitleTV.setTextColor(color);
            }
            mTitleTV.setText(title);
        }
    }


    /**
     * 设置状态栏颜色 4.4以上有效
     * @param colorId
     */
    protected void setStatusColor(int colorId) {
        if (mStatusView != null) {
            mStatusView.setBackgroundResource(colorId);
        }
    }

    /**
     * 设置状态栏的颜色
     * @param colorId
     */
    protected void setToolbarColor(int colorId) {
        if (mToolbar != null) {
            mToolbar.setBackgroundResource(colorId);
        }
    }


    protected abstract int layoutId();


    @Override
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        super.onDestroy();
        gc();
    }


    /**
     * 是否注册eventbus
     * @return
     */
    protected boolean userEventBus() {
        return false;
    }


    /**
     * 使用自动绑定
     * @return
     */
    protected boolean userAutoBindBundle() {
        return false;
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (userAutoBindBundle()) {
            AutoBundle.pack(this, outState);
        }
    }


    /**
     * 自动绑定
     * @param savedInstanceState
     */
    protected void autoBindBundle(Bundle savedInstanceState) {
        if (userAutoBindBundle()) {
            if (savedInstanceState != null) {
                AutoBundle.bind(this, savedInstanceState);
            } else {
                AutoBundle.bind(this);
            }
        }
    }


    /**
     * 订阅eventbus
     */
    protected void registerEventBus() {
        if (userEventBus()) {
            EventBus.getDefault().register(this);
        }
    }


    /**
     * 取消订阅eventbus
     */
    protected void unRegisterEventBus() {
        if (userEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }


    /**
     * 垃圾回收
     */
    protected void gc() {
        unBindView();
        unRegisterEventBus();
        this.mTitleTV = null;
        this.mStatusView = null;
        this.mToolbar = null;
        this.mRootView = null;
        this.mActivity = null;
        this.mUnbinder = null;
    }

    /**
     * 设置屏幕特性
     */
    public void setupWindowsFeature() {
        //默认竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 绑定控件
     */
    protected void bindView() {
        if (userBindView()) {
            mUnbinder = ButterKnife.bind(this);
        }
    }

    /**
     * 解绑控件
     */
    protected void unBindView() {
        if (userBindView() && mUnbinder != null) {
            mUnbinder.unbind();
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        BugtagsManager.onDispatchTouchEvent(this, event);
        return super.dispatchTouchEvent(event);
    }


    /**
     * 是否使用butterknife
     * @return
     */
    protected boolean userBindView() {
        return true;
    }


    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();

    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }


    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }

    @Override
    @CallSuper
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
        //注：回调 1
        BugtagsManager.onResume(this);
    }

    @Override
    @CallSuper
    protected void onPause() {
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        super.onPause();
        BugtagsManager.onPause(this);
    }

    @Override
    @CallSuper
    protected void onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.right_in, R.anim.staty);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.staty, R.anim.right_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.right_in, R.anim.staty);
    }
}
